package net.huashitong.user.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.AppMessage;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.filter.AppMessageFilter;
import net.huashitong.Indicators.service.AppMessageService;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.appsecurity.MD5;
import net.huashitong.until.Until;
import net.huashitong.user.entity.SysValid;
import net.huashitong.user.web.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.huashitong.Indicators.utils.TokenUtil.validateToken;


@Service
public class UserAuthService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AppMessageService appMessageService;

    Logger log = LoggerFactory.getLogger(UserController.class);

    public boolean ifAPPValidate(String userId) {

        String url = "userid=" + userId;
        String ifAppValidate = null;
        try {
            ifAppValidate = Until.HttpGET(Until.IF_APP_VALIDATE + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口：" + Until.IF_APP_VALIDATE + url);
        }
        if (StringUtils.isBlank(ifAppValidate)) {
            log.info("App是否需要安全验证/第三方接口错误，获取失败");
            return false;
        }
        log.info("userauth  " + ifAppValidate);
        JSONObject jsb = JSONObject.parseObject(ifAppValidate);
        log.info("jsb  " + jsb);
        if ("true".equals(jsb.getString("ifvalidate"))) {
            return true;
        } else {
            return false;
        }
    }


    //是否切换设备
    public boolean ifChangeEquip(String oldEquip, String newEquip) {
        if (ObjectUtils.isBlank(oldEquip)) {
            return true;
        }
        if (!oldEquip.equals(newEquip)) {
            return true;
        } else if (oldEquip.equals(newEquip)) {
            return false;
        } else {
            return false;
        }
    }


    //手机验证码校验
    public boolean telValidateCode(String tel, String validCode) {

        SysValid validate = userService.getValidCodeByMobile(tel);
        if (ObjectUtils.isBlank(validate)) {
            return false;
        }
        //当前时间戳与收到验证码的时间间隔（2分钟）
        Long s = System.currentTimeMillis() - Long.parseLong(validate.getTimestamp());
        if (s > 1000 * 60 * 2) {
            return false;
        } else {
            if (validCode.equals(validate.getVaildCode())) {
                return true;
            } else {
                return false;
            }
        }
    }


    //重置密码
    public boolean chongzhi(String tel, String password) {
        String url = "tel=" + tel + "&password=" + password;
        String chongzhi = null;
        try {
            chongzhi = Until.HttpGET(Until.RESET_PWD + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口：" + Until.RESET_PWD + url);
        }
        if (StringUtils.isBlank(chongzhi)) {
            log.info("重置密码接口/第三方接口错误，获取失败");
            return false;
        }
        JSONObject jsb = JSONObject.parseObject(chongzhi);
        if (jsb.getIntValue("returncode") == 200 || jsb.getIntValue("returncode") == 504) {
            log.info("密码修改成功");
            log.info(jsb.toString());
            return true;
        } else {
            String text = jsb.getString("returndata");
            log.info(text);
            log.info(jsb.toString());
            return false;
        }
    }

    //获取用户无查看权限的APP栏目列表
    public JSONArray getNoRightAppMenus(String sysId) {
        UserInfo userInfo = userInfoService.getById(sysId);
        String userId = "";
        JSONArray jsonArray = new JSONArray();
        //用户Id
        if (ObjectUtils.isNotBlank(userInfo.getUserId())) {
            userId = userInfo.getUserId();
        }
        String url = "userid=" + userId;
        String noright = null;
        try {
            noright = Until.HttpGET(Until.GET_NO_RIGHT + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口：" + Until.GET_NO_RIGHT + url);
        }
        if (StringUtils.isBlank(noright)) {
            log.info("获取用户无查看权限的APP栏目列表/第三方接口错误，获取失败");
            return jsonArray;
        }
        JSONArray jsb = JSONObject.parseArray(noright);
        return jsb;
    }

    //获取APP栏目列表
    public JSONArray getAppMenus() {

        JSONArray jsonArray = new JSONArray();
        String appMenus = null;
        try {
            appMenus = Until.HttpGET(Until.GET_APP_MENUS, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口：" + Until.GET_APP_MENUS);
        }
        if (StringUtils.isBlank(appMenus)) {
            log.info("获取APP栏目列表/第三方接口错误，获取失败");
            return jsonArray;
        }
        JSONArray jsb = JSONObject.parseArray(appMenus);
        return jsb;
    }

    //获取未读消息数量
    public int getNoReadMsgCountByUser(String sysId) {
        //不需要传token
        int count = 0;
        //app华通人接口消息个数
        UserInfo userInfo = userInfoService.getById(sysId);
        String user = userInfo.getUserId();
        String url = "user=" + user;
        String myInfos = null;
        try {
            myInfos = Until.HttpGET(Until.GET_MYINFO + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口：" + Until.GET_MYINFO + url);
        }
        if (StringUtils.isBlank(myInfos)) {
            count = 0;
        }else{
            JSONArray jsonArray = JSONObject.parseArray(myInfos);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject job = jsonArray.getJSONObject(i);
                if ("0".equals(job.getString("infostate"))) {
                    count++;
                }
            }
        }
        //app政信云接口消息未读个数
        AppMessageFilter appMessageFilter = new AppMessageFilter();
        appMessageFilter.setReceiver(sysId);
        appMessageFilter.setReadStatus("0");
        List<AppMessage> appMsgs = appMessageService.queryByUserIdOrderCreateDate(appMessageFilter);
        count = count + appMsgs.size();
        return count;
    }

    public Map<String, String> jihuo(String tel, String password, String userid) {
        Map<String, String> map = new HashMap<>();
        String url = "tel=" + tel + "&password=" + password + "&userid=" + userid;
        String jihuo = null;
        try {
            jihuo = Until.HttpGET(Until.JI_HUO + url, 5000, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("接口" + Until.JI_HUO + url);
        }
        if (StringUtils.isBlank(jihuo)) {
            log.info("激活接口/第三方接口错误，获取失败");
            map.put("retruncode", "500");
            return map;
        }
        JSONObject jsb = JSONObject.parseObject(jihuo);
        String retruncode = jsb.getString("returncode");
        String returndata = jsb.getString("returndata");

        map.put("returncode", retruncode);
        map.put("returndata", returndata);

        return map;

    }

    //注册用户到本地
    public boolean registerUserToLocal(String tel, String password, String userid) {
        UserInfo user = userInfoService.getUserInfoByTel(tel);  //电话做判断
        if (ObjectUtils.isNotBlank(user)) {
            if (ObjectUtils.isNotBlank(user.getUserId())) {
                //userId不为空：表里面有数据
                user.setPwd(password);
                userInfoService.update(user);
                return true;
            } else {
                //userId为空：表里面没有数据
                UserInfo userInfo = new UserInfo();
                userInfo.setTel(tel);
                userInfo.setPwd(password);
                userInfo.setRoles("[\"0\"]");
                userInfo.setNoRight("[\"0\"]");
                userInfo.setUserId(userid);
                userInfo.setUserName(userid);
                userInfoService.save(userInfo);
                return true;
            }
        } else {
            //userId为空：表里面没有数据
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setTel(tel);
            userInfo1.setPwd(MD5.md5(password));
            userInfo1.setRoles("[\"luruyuan\"]");
            userInfo1.setNoRight("[\"0\"]");
            userInfo1.setUserId(userid);
            userInfo1.setUserName(userid);
            userInfoService.save(userInfo1);
            return true;
        }


    }


    public String getCodeValid(UserInfo userInfo, String equipCode) {
        //是否需要手势编码code
        String code = "";
        //是否需要安全验证
        boolean needValidate = this.ifAPPValidate(userInfo.getUserId());
        if (needValidate && ObjectUtils.isNotBlank(userInfo.getSsPwd())) {
            //如果token时间为空表示第一次登陆
            if (ObjectUtils.isBlank(userInfo.getLocalTokenTime())) {
                code = "308";
            } else {
                //切换了设备
                if (this.ifChangeEquip(userInfo.getEquipCode(), equipCode)) {
                    //切换设备码，只用手势
                    code = "388";
                } else {
                    //校验token是否过期，false过期，true未过期
                    if (validateToken(userInfo)) {
                        code = "200";
                    } else {
                        //身份过期，手势跟指纹都可以
                        code = "308";
                    }
                }
            }
        } else if (needValidate && ObjectUtils.isBlank(userInfo.getSsPwd())) {
            code = "333";                   //内置用户但是手势密码为空
        } else {
            code = "200";
        }
        return code;
    }
}
